<template>
	<view>
    <view class="header" id="header">
      <view class="navigation">
        <u-icon name="scan" size="28" @click="qRCodeAdd"></u-icon>
        <u-search :show-action="false" v-model="params.deviceNo" placeholder="请输入设备号" class="input"
                  bgColor="rgb(247, 248, 247)" :animation="true" margin="20rpx" searchIconShow="true"
                  showAction="true" @click="search()" @clickIcon="search()" @search="search()"
                  @custom="search()"></u-search>
      </view>

      <view class="stats">
        <text :class="networkType == 0 ? 'optTab' : 'tab'" @click="networkClick(0)">全部（{{totalDevice}}）</text>
        <text :class="networkType == 1 ? 'optTab' : 'tab'" @click="networkClick(1)">在线（{{onlineCount}}）</text>
        <text :class="networkType == 2 ? 'optTab' : 'tab'" @click="networkClick(2)">离线（{{offlineCount}}）</text>
      </view>

      <view class="reply-operate">
        <view class="operate" @click.stop="selectStore()">
          <view class="title">{{storeName}}</view>
          <view>
            <u-icon name="arrow-down" color="rgba(0, 0, 0, 0.5)" size="11"></u-icon>
          </view>
        </view>
      </view>
    </view>
    <store ref="store" @storeData="getStore"></store>
    <scroll-view scroll-y :style="{ height: height + 'px'}" @scrolltolower="reachBottom">
      <view class="content" :class="{popupShow:show}">
        <u-collapse :border="false" @change="changeExpandState" :value="openByDefault"  ref="collapseView">
          <view class="session">
            <view v-for="(item, index) of deviceList" :key="index" :class="expandStateList[index].status=='open'?'open-color session-box':'session-box'">
              <u-collapse-item :name="index" :title="`${item.storeName}`"
                               :value="`离线 ${item.offlineCount}/${item.totalDevice} 台`" :border="false">
                <view class="list" 	v-for="(deviceItem, deviceIndex) of item.deviceList" :key="deviceIndex">
                  <view class="row-top">
                      <u-checkbox-group @change="selectTheDevice($event,deviceItem)">
                        <u-checkbox :disabled="deviceItem.outOfStock==0" :name="deviceItem.id" :checked="deviceItem.checked"></u-checkbox>
                      </u-checkbox-group>
                      <view class="item-name">
                        <text class="u-font-sm">
                          <text>{{deviceItem.deviceTypeName}}</text>
                        </text>
                        <view>{{deviceItem.deviceNo}}</view>
                        <text class="u-font-sm"
                              v-if="deviceItem.remarkName != null && deviceItem.remarkName != ''">({{deviceItem.remarkName}})</text>
                        <view
                            v-if="deviceItem.networkIntensity > 0 && !deviceItem.pulseSwitchState && !$u.test.isEmpty(deviceItem.productId)"
                            class="equipment">串口</view>
                        <view
                            v-else-if="deviceItem.networkIntensity >= 0 && !deviceItem.pulseSwitchState"
                            class="equipment equipment2">串口</view>
                        <view
                            v-if="deviceItem.networkIntensity > 0 && deviceItem.pulseSwitchState"
                            class="equipment">脉冲</view>
                        <view
                            v-else-if="deviceItem.networkIntensity >= 0 && deviceItem.pulseSwitchState"
                            class="equipment equipment2">脉冲</view>
                        <view class="deactivate" v-if="deviceItem.status == 0">已禁用</view>
                        <view class="u-font-sm"
                              v-if="deviceItem.isInsertCoin == 1 && !deviceItem.drDeviceId">
                          （{{deviceItem.rateEach}}{{deviceItem.measuringUnit?deviceItem.measuringUnit:''}}/次）
                        </view>
                        <view class="signal-value"><signal :level="deviceItem.networkIntensity"></signal></view>
                    </view>
                  </view>
                    <view class="right-box" @click.stop="nav('/pages-vending-machine/stockout/stockout?deviceId='+deviceItem.id+'&storeName='+item.storeName)">
                      <text class="outOfStock">缺货({{deviceItem.outOfStock}}个)</text>
                      <u-icon name="arrow-right"  size="32rpx"></u-icon>
                    </view>
                  <view v-if="deviceItem.displayRackItemVoList.length > 0">
                    <view v-for="(data, ind) of deviceItem.displayRackItemVoList" :key="ind">
                      <view class="u-m-b-26" v-show="deviceItem.arrowDoubleShow">
                        <u-row justify="space-between">
                          <u-col span="2">
                            <u--image v-if="data.fileName != null && data.fileName != ''" :src="imgURL+data.fileName"  width="80rpx" height="80rpx" radius="5"></u--image>
                            <u--image v-else :src="staticFileUrl+'/image/common/default_goods_image.svg'" width="80rpx" height="80rpx" radius="5"></u--image>
                          </u-col>
                          <u-col span="6">
                            <text class="u-p-l-10">{{data.commodityName}}</text>
                          </u-col>
                          <u-col span="4">
                            <text class="u-p-l-10">缺货数量：</text> {{data.lackTotalStockNumber}}
                          </u-col>
                        </u-row>
                      </view>
                      <view class="u-m-b-26" v-show="ind < showCommodityIndex && !deviceItem.arrowDoubleShow">
                        <u-row justify="space-between">
                          <u-col span="2">
                            <u--image v-if="data.fileName != null && data.fileName != ''" :src="imgURL+data.fileName"  width="80rpx" height="80rpx" radius="5"></u--image>
                            <u--image v-else :src="staticFileUrl+'/image/common/default_goods_image.svg'" width="80rpx" height="80rpx" radius="5"></u--image>
                          </u-col>
                          <u-col span="6">
                            <text class="u-p-l-10">{{data.commodityName}}</text>
                          </u-col>
                          <u-col span="4">
                            <text class="u-p-l-10">缺货数量：</text> {{data.lackTotalStockNumber}}
                          </u-col>
                        </u-row>
                      </view>
                    </view>
                  </view>
                  <view class="u-flex u-row-center" v-if="deviceItem.displayRackItemVoList.length > 3" @click="bottomDouble(deviceItem.displayRackItemVoList.length,index,deviceIndex,deviceItem.deviceNo)">
                    <image v-if="!deviceItem.arrowDoubleShow" class="double-zao" :src="staticFileUrl+'/image/stats/arrow-bottom-double.png'"> </image>
                    <image v-else class="double-zao" :src="staticFileUrl+'/image/stats/arrow-top-double.png'"> </image>
                  </view>
<!--                  <view v-if="showHeight && deviceItem.displayRackItemVoList.length > 3" style="height: 110rpx"></view>-->
<!--                  <view v-else-if="showHeight && deviceItem.displayRackItemVoList.length == 2" style="height: 80rpx"></view>-->
<!--                  <view v-else-if=" showHeight && deviceItem.displayRackItemVoList.length == 1" style="height: 40rpx"></view>-->
                </view>

                <u-empty v-if="item.deviceList.length == 0" text="暂无设备" mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" />
              </u-collapse-item>
            </view>
          </view>
          <u-empty v-if="deviceList.length == 0" text="暂无设备" mode="list" icon="http://cdn.uviewui.com/uview/empty/list.png" />
        </u-collapse>
        <u-loadmore v-if="deviceList.length > 0" :status="loadStatus" bgColor="#f2f2f2" height="70rpx" line=true> </u-loadmore>
      </view>

    </scroll-view>
    <view class="footer" id="footer">
      <view class="stock-operation">
        <view class="u-flex-center">
          <u-checkbox-group >
            <u-checkbox  label="全选" :checked="params.allSelected" @change="allSelectedOperation">
            </u-checkbox>
          </u-checkbox-group>
        </view>
        <view class="u-flex">
          <u-button text="生成备货单" @click="generateTheInventory" color="#F6F6F6" :customStyle="{width: '210rpx', height: '70rpx', borderRadius: '10rpx',color: '#FFF',backgroundColor:'#6072FF'}"/>
          <u-button text="我的备货单" @click="nav('/pages-vending-machine/inventory/inventory')" color="#F6F6F6" :customStyle="{width: '210rpx', height: '70rpx', borderRadius: '10rpx',color: '#000000CC'}"/>
        </view>
      </view>
    </view>
	</view>
</template>

<script>
  import store from '@/components/store/store.vue';
	export default {
    components: {
      store
    },
		data() {
			return {
        loadStatus: 'nomore',
        imgURL: this.$configPath.imgURL,
        staticFileUrl: this.$configPath.staticFileUrl,
        showCommodityIndex:3,
        showHeight:true,
        params:{
          networkIntensity: -1,
          pageNum: 1,
          pageSize: 10,
          totalPage: 1,
          merchantStoreId:'',
          deviceNo:'',
          deviceIdList:[],
          allSelected:false
        },
        total:0,
        storeName:'设备场地',
        networkType: 0,
        height:0,
        show: false,
        //默认展开列表
        openByDefault: [],
        expandStateList: [],
        //设备
        deviceList:[],
        offlineCount:0,
        onlineCount:0,
        totalDevice:0,
			};
		},
		onReady() {
			this.getPomHeight();
      //console.log("进入了吗1")
		},
		onLoad(option) {
      this.params.deviceIdList=[];
      this.findVendingMachineDevice();
      this.findVendingMachineByConditionAndPage();
      //console.log("进入了吗2")
		},
    mounted() {
     // console.log("进入了吗3")
    },
		methods: {
      reachBottom() {
        if (this.params.pageNum >= this.params.totalPage) {
          return;
        };
        this.loadStatus = 'loading';
        this.params.pageNum++;
        console.log("到底部了:", this.params.pageNum);
        this.findVendingMachineByConditionAndPage();
      },
      bottomDouble(size,index,deviceIndex,deviceNo){
       // console.log(index,'index')
        this.showHeight  = false;
        this.deviceList[index].deviceList[deviceIndex].arrowDoubleShow = !this.deviceList[index].deviceList[deviceIndex].arrowDoubleShow;
        // if(!this.deviceList[index].deviceList[deviceIndex].arrowDoubleShow){
        //   this.deviceNo = deviceNo;
        // }else{
        //   this.deviceNo = -1;
        // }
        this.$nextTick(() => {
          this.$refs.collapseView.init()
        });
      },
      networkClick(index) {
        this.networkType = index;
        this.params.networkIntensity = index;
        this.refresh();
      },
      generateTheInventory(){
        if (uni.$u.test.isEmpty(this.params.deviceIdList)){
            this.$helpers.toast('请至少选择一项');
            return
        }
        uni.showLoading({
          title: '生成中...',
          mask: true
        })
        this.$api('commodityStockRecord.insertInventory', this.params).then(res => {
              uni.stopPullDownRefresh();
              if (res.status == 0) {
                uni.hideLoading();
                this.$helpers.toast('生成备货单成功!');
                let that=this
                setTimeout(function() {
                  that.nav('/pages-vending-machine/inventory/inventory')
                }, 1000);
              } else {
                uni.hideLoading();
                this.$helpers.toast('生成异常:' + res.data.msg);
              }
            }).catch(err => {
              uni.hideLoading();
              uni.stopPullDownRefresh();
          })
      },
      getStore(data) {
        if (data.value) {
            this.storeName = data.label;
            this.params.merchantStoreId = data.value;
            this.refresh();
        }
      },
      changeExpandState(e) {
        this.expandStateList = e;
        this.showHeight  = false;
        //console.log(e)
      },
      //多选 选中设备
      selectTheDevice(e,item){
        if (uni.$u.test.isEmpty(e)){
            this.params.deviceIdList=this.params.deviceIdList.filter(i => i != item.id)
            this.$set(item,'checked',false)
        }else{
            this.params.deviceIdList.push(e[0])
            this.$set(item,'checked',true)
        }
        this.params.allSelected=(this.total==this.params.deviceIdList.length || this.params.deviceIdList.length==this.totalDevice) && this.params.deviceIdList.length!=0
      },
      //全选操作
      allSelectedOperation(){
        this.params.allSelected=!this.params.allSelected;
        this.params.deviceIdList=[];
        //true 选中全部货道
        if (this.params.allSelected){
          this.deviceList.forEach(item=>{
            item.deviceList.forEach(device=>{
              if (device.outOfStock>0){
                  this.$set(device,'checked',true)
                  this.params.deviceIdList.push(device.id);
              }
            })
          })
        }else{
          this.deviceList.forEach(item=>{
            item.deviceList.forEach(device=>{
              this.$set(device,'checked',false)
            })
          })
        }
      },
      //路由跳转
      nav(url){
        uni.navigateTo({
          url: url
        });
      },
      //刷新数据
      refresh(){
        this.deviceList=[];
        this.params.pageNum=1;
        this.findVendingMachineByConditionAndPage();
      },
      //搜索
      search(){
        this.refresh();
      },
      // 统计设备状态数量
      findVendingMachineDevice() {
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        this.$api('device.findVendingMachineDevice', this.params)
            .then(res => {
              uni.stopPullDownRefresh();
              if (res.status == 0) {
                uni.hideLoading();
                this.offlineCount = res.data.offlineCount;
                this.onlineCount = res.data.onlineCount;
                this.totalDevice = res.data.totalDevice;
              } else {
                uni.hideLoading();
                this.$helpers.toast('请求数据失败:' + res.data.msg);

              }
            }).catch(err => {
                uni.hideLoading();
                uni.stopPullDownRefresh();
            })
      },
      //查询设备
      findVendingMachineByConditionAndPage() {
        this.total=0;
        this.params.allSelected=false;
        this.params.deviceIdList=[];
        uni.showLoading({
          title: '加载中...',
          mask: true
        })
        this.$api('device.findVendingMachineByConditionAndPage', this.params)
            .then(res => {
              if (res.status == 0) {
                this.params.pageNum = res.data.pageNum;
                this.params.totalPage = res.data.pages;
                this.loadStatus = res.data.pageNum === res.data.pages ? 'nomore' : 'loadmore';
                if (this.params.pageNum >= res.data.pages) {
                  this.loadStatus = 'nomore';
                }
                this.deviceList = [...this.deviceList, ...res.data.list]; //合并数组
                  for (let i = 0; i < this.deviceList.length; i++) {
                    if (this.deviceList[i].deviceList.length > 0) {
                      let expand = {
                        status: 'open',
                      }
                      this.expandStateList[i] = expand;
                      this.openByDefault = this.openByDefault.concat(i)
                    }
                    this.deviceList[i].deviceList.forEach(item=>{
                      if (item.outOfStock>0){
                        this.total++;
                      }
                    })
                  }
                console.log(" this.deviceList", this.deviceList)
                uni.hideLoading();
              } else {
                uni.hideLoading();
                this.$helpers.toast('请求数据失败:' + res.data.msg);
              }
            })
      },
      selectStore() {
        this.$refs.store.init(true)
      },
      // 调用微信扫一扫
      qRCodeAdd() {

        uni.showLoading({
          title: "正在调起...",
          mask: true
        })

        var that = this;
        uni.scanCode({
          success: function(res) {
            uni.hideLoading();
            // console.log('条码类型：' + res.scanType);
            // console.log('条码内容：' + res.result);
            let array = res.result.split("deviceNo/");
            // console.log("调用扫一扫成功：" + array)

            if (array.length != 2) {
              that.$helpers.toast('二维码不规范：' + res.result);
              return;
            }

            let deviceNo = null;
            // 将扫一扫的结果转化成int类型
            try {
              deviceNo = array[1];
            } catch (e) {
              // console.log("-----转化设备号捕获到异常-------" + e)
              that.$helpers.toast('转化设备号捕获到异常：' + e);
              return;
            }

            if (deviceNo == null || deviceNo == '') {
              // console.log("------转化结果有误------" + deviceNo)
              that.$helpers.toast('转化结果有误：' + deviceNo);
              return;
            }
            // console.log("------转化成功------" + deviceNo)
            that.params.deviceNo = deviceNo;
            that.refresh();
          },
          fail: function() {
            uni.hideLoading();
          }
        });
      },
			// 获取各个盒子的高度
			getPomHeight() {
				let query = wx.createSelectorQuery().in(this)
				query.select('#header').boundingClientRect()
        query.select('#footer').boundingClientRect()
				query.exec(res => {
					let windowHeight = wx.getSystemInfoSync().windowHeight
					this.height = windowHeight
					for (let i = 0; i < res.length; i++) {
						this.height -= res[i].height;

					}
				})

			},
		}
	};
</script>

<style lang="scss"  scoped>
	page {
		background: rgb(239, 239, 239);
	}
  .open-color {
    /deep/ .u-cell__body {
      border-radius: 20rpx 20rpx 0 0;
      background-color: #6072FF;
    }
    /deep/ .uicon-arrow-right,
    /deep/ .u-cell__value,
    /deep/ .u-cell__title-text{
      color: rgb(255, 255, 255);
    }
  }
  .signal-value{
    margin-left: 16rpx;
  }
  .search{
    width: 100%;
    margin-left: 27rpx;
  }
  .right-box{
    display: flex;
    align-items: center;
  }
  .outOfStock{
    color: rgb(127, 140, 255);
    font-size: 30rpx;
    margin-right: 16rpx;
  }
  .footer {
    position: fixed;
    bottom: 0;
    width: 100%;
    background-color: white;
    padding-bottom: 30rpx;
    padding-top: 15rpx;

    /deep/ .u-button--active {
      color: #ffffff !important;
      background: rgb(96, 114, 255) !important;
    }
    .stock-operation{
      display: grid;
      grid-template-columns:1fr 3fr;
      padding: 25rpx 40rpx;
      .choose-text{
        font-size: 32rpx;
        color: rgba(0, 0, 0, 0.8);
      }
    }
  }
  /deep/ .u-input{
    background: rgb(247, 248, 247) !important;
    padding: 15rpx 25rpx 15rpx 22rpx !important;
  }

  .header {
    width: 100%;

    background-color: rgb(255, 255, 255);

    .navigation {
      margin: 0rpx 24rpx 0rpx 24rpx;
      display: flex;
      flex-direction: row;
      justify-content: space-between;
    }

    .stats {
      margin-top: 25rpx;
      display: flex;
      flex-direction: row;
      justify-content: space-between;

      text {
        margin: 0 24rpx 0 22rpx;
        width: 206rpx;
        height: 70rpx;
        font-size: 26rpx;
        border-radius: 20rpx;
        text-align: center;
        line-height: 70rpx;
      }

      .optTab {
        background-color: rgb(96,114,255);
        color: $uni-text-color-inverse;
      }

      .tab {
        background-color: rgb(244, 247, 255);
        color: rgba(0, 0, 0, 0.7);
      }
    }

    .reply-operate {
      padding: 27rpx 0 22rpx 24rpx;
      color: rgba(13, 13, 13, 0.5);
      display: flex;
      flex-direction: row;
      font-size: 26rpx;

      .operate {
        display: flex;
        align-items: center;

        .title {
          margin-right: 10rpx;
        }
      }

      .operate-right {
        padding-left: 100rpx;
      }

      .operate-m-right {
        margin-left: 100rpx;
      }

      .reply-add {
        margin-left: 9rpx;
      }

      .sync {
        color: rgba(13, 13, 13, 0.5);
      }
    }
  }
  .content {
    margin-top: 22rpx;
    width: 100%;
    background: #F2F2F2;
    .session {
      //background-color: white;
      .double-zao{
        width: 52rpx;
        height: 52rpx;
      }
      font-size: 26rpx;
      padding: 0 24rpx;

      .right-arrow {
        margin-right: 15rpx;
      }

      .device {
        margin-left: 5rpx;
      }

      .session-box {
        border-radius: 20rpx;
        background-color: #FFFFFF !important;
        margin-bottom: 20rpx;

        /deep/ .u-cell__body {
          padding: 40rpx 28rpx !important;
        }

        .equipment {
          color: rgb(7, 213, 176);
          margin-left: 8rpx;
          display: flex;
          align-items: center;
          justify-content: center;
          font-size: 22rpx;
          width: 60rpx;
          height: 30rpx;
          box-sizing: border-box;
          border: 1rpx solid rgb(7, 213, 176);
          border-radius: 6rpx;
        }

        .deactivate {
          font-size: 22rpx;
          margin-left: 8rpx;
          border: 1rpx solid rgb(255, 77, 79);
          color: rgb(255, 77, 79);
          border-radius: 6rpx;
          box-sizing: border-box;
          width: 80rpx;
          height: 30rpx;
          display: flex;
          align-items: center;
          justify-content: center;
        }

        .equipment2 {
          border: 1rpx solid #c8c7cc;
          background-color: #f4faff;
          color: rgba(0, 0, 0, 0.7)
        }

        .item-name {
          display: flex;
          align-items: center;
          color: rgba(0, 0, 0, 0.7);
          flex-wrap: wrap;
        }

        .showcase {
          color: rgba(0, 0, 0, 0.5);
          font-size: 24rpx;
        }

        .batch-set {
          text-align: right;
          color: #6072FF;
        }

        .list {
          //flex-wrap: wrap;
          //display: flex;
          //justify-content: space-between;
          line-height: 60rpx;
          //background: rgb(244, 250, 255);
          border-radius: 20rpx;
          margin-bottom: 20rpx;
          padding: 26rpx 0rpx;


            .row-top {
              display: flex;

              .u-font-xl {
                font-weight: bold;
              }

              .u-margin-left-20 {
                color: black;
              }

            }

            .giftType {
              display: flex;
              justify-content: space-between;

              .commodity-img {
                width: 100rpx;
                height: 100rpx;
                background-color: rgb(246, 246, 246);
                border-radius: 8rpx;

                .wei-ban-ding {
                  width: 80rpx;
                  height: 80rpx;

                  /deep/ .u-icon {
                    justify-content: center;
                  }

                  .wei-bang-ding-text {
                    color: rgba(0, 0, 0, 0.5);
                    font-size: 20rpx;
                  }
                }
              }

              .drDeviceId {
                width: 530rpx;
                display: flex;
                justify-content: space-between;
                .view-drDeviceId {
                  // margin: 6rpx;
                  border-radius: 8rpx;
                  width: 170rpx;
                  background-color: rgb(246, 246, 246);
                  padding: 10rpx;
                  height: 100rpx;
                  box-sizing: border-box;

                  .drDeviceId-num,
                  .drDeviceId-name {
                    line-height: 40rpx;
                  }

                  .drDeviceId-num {
                    font-size: 24rpx;
                    color: rgba(0, 0, 0, 0.8);
                  }

                  .drDeviceId-name {
                    font-size: 20rpx;
                    color: rgba(0, 0, 0, 0.5);
                  }
                }

                .view-drDeviceId-width{
                  width: 153rpx;
                }
              }
            }

            .row-bottom {

              display: flex;
              justify-content: space-between;
            }

        }
      }


      /deep/ .u-empty {
        padding-bottom: 20rpx;
      }
    }
  }

</style>
